package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.dto.input.MetaSystemUnitValueInputDto;
import com.b511.swpu.cementbackend.entity.MetaSystemUnitValue;
import com.b511.swpu.cementbackend.exception.CementException;
import com.b511.swpu.cementbackend.repository.MetaSystemUnitValueRepository;
import com.b511.swpu.cementbackend.service.MetaSystemUnitValueService;
import com.b511.swpu.cementbackend.util.enumeration.Code;
import com.b511.swpu.cementbackend.util.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MetaSystemUnitValueServiceImpl implements MetaSystemUnitValueService {

    private final MetaSystemUnitValueRepository metaSystemUnitValueRepository;

    public MetaSystemUnitValueServiceImpl(MetaSystemUnitValueRepository metaSystemUnitValueRepository) {
        this.metaSystemUnitValueRepository = metaSystemUnitValueRepository;
    }

    @Override
    public R getMetaSystemUnitValueById(Long id) {
        List<MetaSystemUnitValue> result = metaSystemUnitValueRepository.findByMetaSystemUnit_Id(id);
        if (null == result) {
            throw new CementException(Code.SELECT_FAIL);
        }
        return R.ok().putData(result);
    }

    @Override
    @Transactional
    public R updateMetaSystemUnitValue(List<MetaSystemUnitValueInputDto> list) {
        for (MetaSystemUnitValueInputDto metaSystemUnitValueInputDto : list) {
            metaSystemUnitValueRepository.updateMetaSystemUnitValue(metaSystemUnitValueInputDto.getUnitId(), metaSystemUnitValueInputDto.getUnitCategoryValueId());
        }
        return R.ok();
    }
}
